//
//  ViewController.swift
//  demo1-动力学
//
//  Created by 刘文超 on 2020/5/29.
//  Copyright © 2020 刘文超. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    
    
   private lazy var itemView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.red
        return view
    }()
    
    //MARK:一个对象，为其动态项目提供与物理相关的功能和动画，并为这些动画提供上下文。是UIKit物理引擎。此类跟踪您添加到引擎的各种行为，例如重力，并提供整体上下文。在创建动画制作器的实例时，可以传入animator用来定义其坐标系的参考视图。
    var dynamic:UIDynamicAnimator?
    //MARK:向所有关联的动态项目施加类似重力的对象。模拟重力的行为并对一个或多个项目施加力，允许您对物理交互进行建模
    var gravheave:UIGravityBehavior!
    //MARK:设置边界
    var collsionBody:UICollisionBehavior!
    
    var snap:UISnapBehavior!
    
    
    
    //MARK:障碍试图
    private lazy var zhanaiView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.blue
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Invisible boundaries and collisions - 不可见的边界和碰撞
        
        view.backgroundColor = UIColor.white
        //运动试图
        view.addSubview(itemView)
        itemView.frame = CGRect(x: 150, y: 150, width: 60, height: 60)
        //障碍试图
        view.addSubview(zhanaiView)
        zhanaiView.frame = CGRect(x: 0, y: 300, width: 280, height: 30)
        
        
        
        dynamic = UIDynamicAnimator(referenceView: view)
        //添加重力行为
        gravheave = UIGravityBehavior(items: [itemView])
        dynamic?.addBehavior(gravheave)
        //添加边界行为
        collsionBody = UICollisionBehavior(items: [itemView])
//        collsionBody.translatesReferenceBoundsIntoBoundary = true
        collsionBody.action = {
            print("111111")
        }
        collsionBody.collisionDelegate = self
        let bezipath = UIBezierPath(rect: zhanaiView.frame)
        //调不起来啊
        collsionBody.addBoundary(withIdentifier: <#T##NSCopying#>, for: bezipath)
        dynamic?.addBehavior(collsionBody)
        
        //滑块行为
        let behavi = UIDynamicItemBehavior(items: [itemView])
        behavi.elasticity = 0.6
        dynamic?.addBehavior(behavi)
        
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if snap != nil {
            dynamic?.removeBehavior(snap)
        }
        
        let touch = touches.first!
        snap = UISnapBehavior(item: itemView, snapTo:touch.location(in: view))
        dynamic?.addBehavior(snap)
    }


}


extension ViewController:UICollisionBehaviorDelegate {
    
    func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
        print("开始碰撞")
        let view  = item as! UIView
        view.backgroundColor = UIColor.purple
        UIView.animate(withDuration: 0.5) {
             view.backgroundColor = UIColor.green
        }
    }
}

extension ViewController {
    
    
}

